package cn.sourcespro.spring.config;

import cn.sourcespro.spring.util.RespUtil;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * security
 *
 * @author zhanghaowei
 * @date 2018/7/26
 */
public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        if (authException instanceof UsernameNotFoundException) {
            RespUtil.send(response, "无效的用户名", HttpStatus.FORBIDDEN);
        }
        if (authException instanceof BadCredentialsException) {
            RespUtil.send(response, "密码错误", HttpStatus.FORBIDDEN);
        }
        RespUtil.send(response, "没有访问权限", HttpStatus.FORBIDDEN);
    }
}
